import React, { Component } from "react";
import { Table, Badge, DatePicker, Input } from "antd";
import moment from "moment";
import { Link } from "dva/router";
import { connect } from "dva";
import tableFilter from "../../../components/tableFilter";

import styles from "./index.less";

const { RangePicker } = DatePicker;
const { Search } = Input;

@connect(stores => ({
  systemManager: stores.systemManager
}))
@tableFilter
class BacklogPage extends Component {
  state = {
    ownerDepts: [],
    stateHandles: [],
    pushChannels: [],
    orderBy: "time_create desc",
    timeStart: "",
    timeEnd: "",
    userOrPlan: "",
    pageNum: 1,
    pageSize: 10,
    totalCount: 0,
    loading: false
  };

  componentDidMount() {
    this.getData();
    this.getFilterData();
  }

  dateChange = (e = []) => {
    this.setState(
      {
        timeStart: e.length ? e[0].format("YYYY-MM-DD 00:00:00") : undefined,
        timeEnd: e.length ? e[1].format("YYYY-MM-DD 23:59:59") : undefined,
        pageNum: 1
      },
      () => {
        this.getData();
        this.getFilterData();
      }
    );
  };

  handleTableChange = (
    e,
    { ownerDeptName, stateHandle, pushChannelName },
    { order, field }
  ) => {
    const { current, pageSize } = e;
    const { ownerDepts, stateHandles } = this.state;
    const order2 = order && order === "ascend" ? "asc" : "desc";
    const orderField = field === "timeHandle" ? "time_handle" : "time_create";
    const orderBy = `${orderField} ${order2}`;
    this.setState(
      {
        pageNum:
          (ownerDeptName && ownerDeptName !== ownerDepts) ||
          (stateHandle && stateHandle !== stateHandles) ||
          (pushChannelName && pushChannelName !== stateHandles)
            ? 1
            : current,
        pageSize,
        orderBy,
        ownerDepts: ownerDeptName || [],
        stateHandles: stateHandle || [],
        pushChannels: pushChannelName || []
      },
      () => {
        this.getData();
        this.getFilterData();
      }
    );
  };

  handleSearch = e => {
    this.setState(
      {
        userOrPlan: e,
        pageNum: 1
      },
      () => {
        this.getData();
        this.getFilterData();
      }
    );
  };

  clearChange = e => {
    if (e.target.value !== "") return;
    this.setState(
      {
        userOrPlan: "",
        pageNum: 1
      },
      () => {
        this.getData();
        this.getFilterData();
      }
    );
  };

  // 获取筛选下拉列表
  getFilterData = () => {
    const { dispatch } = this.props;
    const {
      timeStart,
      timeEnd,
      userOrPlan,
      ownerDepts,
      stateHandles,
      orderBy,
      pushChannels
    } = this.state;
    const params = {
      timeStart,
      timeEnd,
      userOrPlan,
      ownerDepts,
      stateHandles,
      pushChannels,
      orderBy
    };
    dispatch({
      type: "systemManager/fetchBackDepList",
      payload: { ...params }
    });
    dispatch({
      type: "systemManager/fetchBackChannelList",
      payload: { ...params }
    });
  };

  // 获取列表数据
  getData = () => {
    const {
      timeStart,
      timeEnd,
      ownerDepts,
      stateHandles,
      pushChannels,
      orderBy,
      userOrPlan,
      pageNum,
      pageSize
    } = this.state;
    const { dispatch } = this.props;
    this.setState({
      loading: true
    });
    const params = {
      timeStart,
      timeEnd,
      userOrPlan,
      ownerDepts,
      stateHandles,
      pushChannels,
      orderBy,
      pageNum,
      pageSize
    };
    dispatch({
      type: "systemManager/fetchBackLogList",
      payload: { ...params }
    }).then(totalCount => {
      this.setState({
        totalCount,
        loading: false
      });
    });
  };

  renderState = text => {
    if (text === 1) {
      return <Badge status="success" text="审批通过" />;
    }
    if (text === -1) {
      return <Badge status="default" text="未通过" />;
    }
    return <Badge status="warning" text="待审批" />;
  };

  handleDisabledDate = current => current < moment().subtract(6, "months");

  render() {
    const {
      systemManager: {
        backLogList = [],
        backDepFilter = [],
        backStateFilter = [],
        backChannelFilter = []
      },
      getColumnSearchProps = () => {}
    } = this.props;
    const { loading, pageNum, totalCount } = this.state;
    const columns = [
      {
        title: "计划名称",
        dataIndex: "planName",
        render: text => <span title={text}>{text}</span>
      },
      {
        title: "推送场景",
        dataIndex: "templateName",
        render: text => <span title={text}>{text}</span>
      },
      {
        title: "推送渠道",
        dataIndex: "pushChannelName",
        filters: backChannelFilter,
        filterMultiple: false
      },
      {
        title: "归属部门",
        dataIndex: "ownerDeptName",
        filters: backDepFilter,
        filterMultiple: false,
        ...getColumnSearchProps(backDepFilter),
        render: text => <span title={text}>{text}</span>
      },
      {
        title: "管理员",
        dataIndex: "owner",
        render: text =>
          JSON.parse(text) && JSON.parse(text).length > 0
            ? JSON.parse(text)[0].name
            : "-"
      },
      {
        title: "状态",
        dataIndex: "stateHandle",
        filters: backStateFilter,
        filterMultiple: false,
        render: text => <div>{this.renderState(text)}</div>
      },
      {
        title: "提交时间",
        dataIndex: "timeCreate",
        sorter: true,
        ellipsis: true,
        defaultSortOrder: "descend",
        render: text =>
          text ? moment(text).format("YYYY-MM-DD HH:mm:ss") : "---"
      },
      {
        title: "审批时间",
        dataIndex: "timeHandle",
        sorter: true,
        ellipsis: true,
        defaultSortOrder: "descend",
        render: text =>
          text ? moment(text).format("YYYY-MM-DD HH:mm:ss") : "---"
      },
      {
        title: "操作",
        dataIndex: "operate",
        fixed: "right",
        width: 100,
        render: (text, record) => {
          const states = {
            operate: "audit",
            planId: record.specificEventId,
            pendingEventId: record.pendingEventId
          };
          const detail = {
            operate: "detail",
            planId: record.specificEventId,
            pendingEventId: record.pendingEventId
          };
          return (
            <span>
              {record.stateHandle === 0 ? (
                <Link
                  to={`/systemManager/systemManage/backLog/planDetail?key=${JSON.stringify(
                    states
                  )}`}
                >
                  审批
                </Link>
              ) : (
                <Link
                  to={`/systemManager/systemManage/backLog/planDetail?key=${JSON.stringify(
                    detail
                  )}`}
                >
                  查看详情
                </Link>
              )}
            </span>
          );
        }
      }
    ];
    return (
      <div className={styles.root}>
        <div
          style={{
            fontSize: 14,
            color: "rgba(0,0,0,0.85)",
            marginBottom: 16,
            display: "flex",
            justifyContent: "flex-end",
            alignItems: "center"
          }}
        >
          提交时间：
          <RangePicker
            style={{ width: 224, marginRight: 21 }}
            onChange={this.dateChange}
            disabledDate={this.handleDisabledDate}
          />
          <Search
            placeholder="计划名称、管理员姓名"
            style={{ width: 272 }}
            onSearch={this.handleSearch}
            allowClear
            onChange={this.clearChange}
          />
        </div>
        <Table
          rowKey={record => record.pendingEventId}
          columns={columns}
          scroll={backLogList.length===0?{x:false}:{ x: 1200 }}
          dataSource={backLogList}
          locale={{ emptyText: "暂无数据！" }}
          size="middle"
          onChange={(e, filters, sorter) =>
            this.handleTableChange(e, filters, sorter)
          }
          loading={loading}
          pagination={{
            defaultPageSize: 10,
            showQuickJumper: true,
            showSizeChanger: true,
            current: pageNum,
            total: totalCount,
            showTotal: total => `共有 ${total} 条`
          }}
        />
      </div>
    );
  }
}

export default BacklogPage;
